<template>
  <el-dialog :visible.sync="show" destroy-on-close :title="title" :width="width" :center="center" :draggable="draggable"
             show-footer>
    <template #default>
      <el-form :model="formData" ref="formRef" label-width="80px" class="el-form-globals">
        <el-row>
          <el-col :xs="24" :sm="4" :md="4" :lg="4">
            <div class="static-content-item">
              <el-upload
                  ref="uploadRef"
                  :action="formData.action"
                  :show-file-list="false"
                  :on-success="onChange"
              >
                <el-button>上传预览
                  <el-icon class="el-icon--right">
                    <Upload/>
                  </el-icon>
                </el-button>
              </el-upload>
            </div>
          </el-col>
          <el-col :xs="24" :sm="4" :md="4" :lg="4">
            <div class="static-content-item">
              <el-button @click="submit">立即上传
                <el-icon class="el-icon--right">
                  <Upload/>
                </el-icon>
              </el-button>
            </div>
          </el-col>
          <el-col :xs="24" :sm="4" :md="4" :lg="4">
            <div class="static-content-item">
              <el-button @click="download">下载模板
                <el-icon class="el-icon--right">
                  <Download/>
                </el-icon>
              </el-button>
            </div>
          </el-col>
          <el-col :xs="24" :sm="4" :md="4" :lg="4">
            <div class="static-content-item">
              <el-button :disabled="formData.disabled" :class="formData.selected_but"
                         @click="batchRemove">批量删除
                <el-icon class="el-icon--right">
                  <Delete/>
                </el-icon>
              </el-button>
            </div>
          </el-col>
          <el-col :xs="24" :sm="8" :md="8" :lg="8">
            <el-form-item label="校验唯一" prop="uniCode">
              <el-select v-model="formData.uniCode" @change="handleChange" class="full-width-input" clearable>
                <el-option v-for="(item, index) in gridOptions.columns.filter(o=>o.field)" :key="index"
                           :label="item.title"
                           :value="item.title" :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <vxe-grid style="width: 100%" ref='xGrid' v-bind="gridOptions" @checkboxChange="selectRowChange"
                    @checkboxAll="selectRowChange"/>
        </el-row>
      </el-form>
    </template>
    <template #footer>
      <el-button @click="close">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script>
import {get, request} from "@/utils/http/httpUtils";
import {exportExcel} from "@/utils/ExcelUtil";
import {mapGetters} from 'vuex';

export default {
  name: 'olDialogImport',
  inject: ['http'],
  props: {
    title: {
      default: '导入数据'
    },
    name: {
      default: '导入数据'
    },
    width: {
      default: 800
    },
    draggable: {
      default: true
    },
    center: {
      default: false
    },
    selectData: {
      default: '1'
    }
  },
  ...mapGetters('dict', ['val']),
  ...mapGetters('dictType', {dictTypeVal: 'val'}),
  data() {
    return {
      form: {selectData: ''},
      tableConfigId: '',
      show: '',
      formData: {},
      gridOptions: {
        border: true,
        keepSource: true,
        showOverflow: true,
        loading: false,
        height: 330,
        align: 'left',
        scrollX: {enabled: true, gt: 15},
        scrollY: {enabled: true, gt: 0},
        columnConfig: {
          resizable: true
        },
        rowConfig: {
          useKey: true,
          keyField: 'id',
        },
        expandConfig: {
          labelField: 'seq'
        },
        editConfig: {
          trigger: 'click',
          mode: 'row',
          showStatus: true,
        },
        checkboxConfig: {
          labelField: 'title',
          reserve: true,
          highlight: true,
          range: true,
          checkAll: false
        },
        columns: [],
        data: [],
        toolbarConfig: {},
        initColumns: [
          {type: 'checkbox', width: 50, fixed: 'left'},
          {type: 'seq', title: '序号', width: 50, fixed: 'left'}
        ],
      },
      genIdMap: undefined,
      url: '/online/crud/batchSave',
    }
  },
  methods: {
    submit() {
      if (!this.gridOptions.data || this.gridOptions.data.length == 0) return this.$message.error('导入数据为空！')
      let params = this.getParams();
      this.gridOptions.loading = true
      request(this.http, {
        url: this.url,
        method: 'post',
        data: params,
        timeout: 1000 * 90 * 90
      }, false, false).then(({msg, code}) => {
        if (code == 200) {
          this.show = false
          this.$emit('emits', {m: 'query'})
          this.$message.success(msg);
        } else {
          this.$message.error(msg);
        }
      }).finally(() => {
        this.gridOptions.loading = false;
      })
    }, open({column, tableConfigId, json}) {
      if (json) {
        if (json.genIdMap) {
          this.genIdMap = json.genIdMap
        }
        if (json.url) {
          this.url = json.url
        }
      }
      this.tableConfigId = tableConfigId;
      this.show = true
      let columns = column.filter(o => o.columnAuth == 1)
      columns.push(...this.gridOptions.initColumns)
      this.gridOptions.data=[]
      this.gridOptions.columns = columns;
      this.$refs.xGrid.loadColumn(this.gridOptions.columns)
    },
    handleChange(title) {
      let que = [];
      for (let j = 0; j < this.gridOptions.data.length; j++) {
        let data = this.gridOptions.data[j];
        if (j == 0) {
          que.push(data[title])
          break
        }
        let index = que.index0f(data[title]);
        if (index != -1) {
          return this.$message.warn('第' + (j + 1) + '行-第' + (index + 1) + '行数据不唯-:' + data[title])

        }
        que.push(data[title])
      }
      this.$message.success(title + '无重复数据!');
    },
    selectRowChange() {
      this.formData.disabled = this.$refs.xGrid.getCheckboxRecords(true).length == 0
      this.formData.selected_but = this.formData.disabled ? 'unselected_but' : 'selected_but'
    },
    batchRemove() {
      let records = this.$refs.xGrid.getCheckboxRecords(true);
      if (!records || records.length == 0) return this.$message.error('未选中数据！')
      this.$refs.xGrid.removeCheckboxRow()
    },
    getParams() {
      return {
        tableConfigId: this.tableConfigId,
        genIdMap: this.genIdMap,
        columnAndValueListMap: this.getDataByDict(this.gridOptions.data)
      }
    }, onChange({data}) {
      data = this.getDataByTitle(data)
      this.gridOptions.data = data
    },
    getDataByTitle(data) {
      if (data && data.length >= 1) {
        let rows = []
        data.map(row => {
          let obj = {}
          for (let key in row) {
            this.gridOptions.columns.forEach((item) => {
              if (item.title == key) {
                obj[item.field] = row[key]
              }
            })
          }
          rows.push(obj)
        })
        return rows
      }
    },
    getDataByDict(data) {
      if (data && data.length >= 1) {
        let rows = []
        data.map(row => {
          let obj = {}
          for (let key in row) {
            this.gridOptions.columns.forEach((item) => {
              if (item.field == key) {
                obj[item.field] = this.getRowValue(item.dictCode, row[key])
              }
            })
          }
          rows.push(obj)
        })
        return rows
      }
    },
    download() {
      exportExcel({
        data: [],
        name: '模板下载',
        columns: this.gridOptions.columns.filter(o => o.field),
        option: {align: 'center'}
      })
    },
    init(id) {
      this.gridOptions.loading = true
      get(this.http, this.gridOptions.url, {id: id}, true).then(res => {
        for (const data of res) {
          data.width = 100
        }
        res.push(...this.gridOptions.initColumns)
        this.gridOptions.columns = res
        this.gridOptions.loading = false
      })
    },
    getRowValue(dictCode, val) {
      if (dictCode) {
        return this.getDictValueByCode(dictCode, val);
      }
      return val
    },
    getDictValueByCode(dictCode, val) {
      for (const option of this.val(dictCode)) {
        if (option.label == val) {
          return option
        }
      }
      return val
    },
    close() {
      this.show = false
    }
  }, created() {
    var headers = this.http.axios().defaults.headers;
    console.log(headers)
    this.formData = {
      action: this.http.axios().defaults.baseURL + '/online/crud/upload',
      uniCode: '',
      headers: headers,
      disabled: true,
      selected_but: 'unselected_but'
    }
  }
}
</script>
<style lang="less" scoped>
.el-form-item__content {
  display: flow;
}

.selected_but {
  background-color: #f56c6c;
}

.unselected_but {
  background-color: #fbcccc;
}
</style>
